# Make uses /bin/sh as default shell. Chenge to /bin/bash to support
# wildcard expansion in commands.
SHELL=/bin/bash

# The path to the DOKK "data" repository.
# This is used by some sources instead of downloading the repository.
DOKK-DATA=$(realpath ../data)

# List of all sources.
# A source is the name of the sub-directory in ./source
SOURCE=$(shell find ./source/ -mindepth 1 -maxdepth 1 -type d -exec basename {} \;)

# Build all sources.
# Documentation for "Automatic Variables": https://www.gnu.org/software/make/manual/html_node/Automatic-Variables.html#Automatic-Variables
${SOURCE}:
	@ # Do not print commands

	if [ ! -d "${DOKK-DATA}" ]
	then
		echo "DOKK-DATA doesn't exist!"
		exit
	fi
	
        # Run a source Makefile in its sub-directory.
        # The job of each subdirectory is to create a data/ directory
        # containing all the required RDF files.
	${MAKE} DOKK-DATA=${DOKK-DATA} --directory ./source/$@

        # Merge all RDF data into single .nt file.
        # This code will create a .nt file in the source directory. For example,
        # if the source name ($@) is "grid", will create ./source/grid/grid.nt.
        # This process assumes that all input triples are valid (no syntax errors).
        # NB: we use - in front of "find" because RIOT does not return 0
        #     if it raised any warnings. "Make" aborts execution if it sees
        #     a return code other than 0, but we are OK with RIOT warnings.
	-find ./source/$@/data/ \
		-type f \
		-exec riot --base "#" \
			   --check \
			   --strict \
			   --stop \
			   --output nq \
			   {} > ./source/$@/$@.nt \
		+

	# Delete old source dataset
	echo "Deleting $@ dataset."
	rm --recursive --force ./dataset/$@/
	
        # Now build a TDB2 dataset for this source
	tdb2.tdbloader --loc ./dataset/$@/ ./source/$@/$@.nt

# Build the DOKK graph from queries
graph:
	@ # Do not print commands
	
	echo "Deleting dokk dataset."
	rm --recursive --force dataset/dokk/
	
	# Execute queries in order!
	for query in RadioChannel License rdf-prefixes manpages \
		     library articles documentation
	do
		echo "Processing: $${query}"
		update --desc dataset.ttl --update "query/$${query}.rq"
	done

clean:
	rm --recursive --force dataset

.ONESHELL:
.PHONY: $(SOURCE) clean
